package com.ys.controller.web.purchase;

import com.ys.config.MenuId;
import com.ys.dto.SubGridConfigDto;
import com.ys.entity.purchase.TcgPurchaseAddress;
import com.ys.entity.purchase.TcgPurchaseByPlan;
import com.ys.service.flow.YspTaskService;
import com.ys.service.purchase.TcgPurchaseByPlanService;
import com.ys.service.sys.CommonApiService;
import com.ys.vo.Flow;
import com.ys.vo.W;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 采购计划单
 */
@Controller
@RequestMapping("/web/purchase/tcgPurchaseByPlan")
public class WebTcgPurchaseByPlanController {
	private static final Logger logger = LoggerFactory.getLogger(WebTcgPurchaseByPlanController.class);

	@Autowired
	private CommonApiService<TcgPurchaseByPlan> commonApiService;

    @Autowired
    private YspTaskService yspTaskService;

    @Autowired
    private TcgPurchaseByPlanService tcgPurchasePlanService;

    private final Long MENU_ID = MenuId.TCG_PurchaseByPlan;

    /*
     * 新增
     */
    @GetMapping("/toAdd")
    public String toAdd(Model model, HttpServletRequest request, HttpServletResponse response) {
        try {
            Map<String, Object> extraParam = new HashMap<>();
            //关联数据
            extraParam.put("status", 1);
            extraParam.put("isJgSub", 0);

            TcgPurchaseByPlan entity = new TcgPurchaseByPlan();
            //关联数据
            String bid = commonApiService.getCommonNextBid(MENU_ID);
            entity.setBid(bid);

            //采购地址默认第一条
            TcgPurchaseAddress tcgPurchaseAddress = new TcgPurchaseAddress().setStatus(1).setOrderby("A.Id").queryFirst();
            extraParam.put("purchaseAddressId", tcgPurchaseAddress.getId());
            extraParam.put("addressDetail", tcgPurchaseAddress.getVGjH() + "," + tcgPurchaseAddress.getVSfH()
                    + "," + tcgPurchaseAddress.getVDsH() + "," + tcgPurchaseAddress.getVCqH() + "," + tcgPurchaseAddress.getVDzH());

            // 子列表配置信息
            SubGridConfigDto subGridConfig = commonApiService.getSubGrid(MENU_ID,new ArrayList<>());
             commonApiService.toAdd(model, entity, MENU_ID, extraParam, subGridConfig);

            return "purchase/tcgPurchasePlan/toAdd";
        }catch (Exception e) {
            logger.error("新增页面出错：",e.getMessage(),e);
            return W.error(model, e.getMessage());
        }
    }

    /*
     * 编辑
     */
    @GetMapping("/toEdit")
    public String toEdit(Model model, HttpServletRequest request, HttpServletResponse response, String bid) {
        try {
            Map<String, Object> extraParam = tcgPurchasePlanService.getExtraParam(bid);

            List<Map<String, Object>> itemList = tcgPurchasePlanService.getItemListByBid(bid);
            // 子列表配置信息
            SubGridConfigDto subGridConfig = commonApiService.getSubGrid(MENU_ID,itemList);

            //子表按钮
            Integer state = yspTaskService.flowState(bid);
            if (state == Flow.State.FINISH.value){
                subGridConfig.setButtonArr(new ArrayList<>());
            }else if (state == Flow.State.PROCESS.value){
                subGridConfig.setButtonArr(new ArrayList<>());
            }
            commonApiService.toEdit(model,Long.parseLong(extraParam.get("id").toString()), new TcgPurchaseByPlan(), MENU_ID, extraParam, subGridConfig);
            return "purchase/tcgPurchasePlan/toEdit";

        }catch (Exception e) {
            logger.error("编辑页面出错：",e.getMessage(),e);
            return W.error(model, e.getMessage());
        }
    }





    public Map<String,Object> getExtraParam(String bid){
        Map<String,Object> extraParam = new TcgPurchaseByPlan()

                .addLeftJoin("YS_ProcInst P ON P.Bid = A.Bid ")
                .addField("FORMAT(P.UpdateTime, 'yyyy-MM-dd HH:mm:ss') AS auditingTime")//审核时间

                .addLeftJoin("THR_OperateCompanyApply D ON D.Vgsbm = A.Vgsbm ")//运营公司管理表
                .addField("D.Vgsjc AS vgsjc")//采购公司简称
                .addField("D.Vgsmc AS vgsmc")//采购公司名称
                .addField("D.VgsSh AS vgsSh")//采购公司税号

                .addLeftJoin("TCG_PurchaseAddress E ON E.Id = A.PurchaseAddressId ")//采购地址维护
                .addField("E.VGjH + ',' + E.VSfH + ',' + E.VDsH + ',' + E.VCqH + ',' + E.VDzH  AS addressDetail")//地址详情

                .addLeftJoin("(SELECT SUM((H.PurchaseAmount + H.JgSl) * H.Bprice) AS totalPrice,H.Pbid FROM TCG_PurchaseByPlanSon H GROUP BY H.Pbid) I ON I.Pbid = A.Bid")
                .addField("I.TotalPrice AS totalPrice")//采购预估金额

                .setBid(bid)
                .queryFirstMap();

        return extraParam;
    }


}






